package com.zh.common.exception;


import cn.hutool.core.date.DateUtil;
import com.zh.common.entity.JSONResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * code is far away from bug with the animal protecting
 * ┏┓　　　┏┓
 * ┏┛┻━━━┛┻┓
 * ┃　　　　　　　┃
 * ┃　　　━　　　┃
 * ┃　┳┛　┗┳　┃
 * ┃　　　　　　　┃
 * ┃　　　┻　　　┃
 * ┃　　　　　　　┃
 * ┗━┓　　　┏━┛
 * 　　┃　　　┃神兽保佑
 * 　　┃　　　┃代码无BUG！
 * 　　┃　　　┗━━━┓
 * 　　┃　　　　　　　┣┓
 * 　　┃　　　　　　　┏┛
 * 　　┗┓┓┏━┳┓┏┛
 * 　　　┃┫┫　┃┫┫
 * 　　　┗┻┛　┗┻┛
 *
 * @version 1.0
 * @Description : 全局异常处理器
 * @Author : chenfei
 * @Create in : 2020/11/6 14:40
 */
@ControllerAdvice
public class ErrorExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(ErrorExceptionHandler.class);

    /**
     * Controller异常返回结果
     * @param e
     * @return
     */
    @ExceptionHandler(value = MyControllerException.class)
    @ResponseBody
    public JSONResult<Object> controllerHandlerException(MyControllerException e){
        JSONResult<Object> result = new JSONResult<>();
        result.setCode(e.getCode());
        result.setMessage(e.getMessage());
        result.setSuccess(e.isFlag());
        result.setTime(DateUtil.now());
        log.error(e.getMessage());
        return result;
    }


    /**
     * Service异常返回结果
     * @param e
     * @return
     */
    @ExceptionHandler(value = MyServiceException.class)
    @ResponseBody
    public JSONResult<Object> serviceHandlerException(MyServiceException e){
        JSONResult<Object> result = new JSONResult<>();
        result.setCode(e.getCode());
        result.setMessage(e.getMessage());
        result.setSuccess(e.isFlag());
        result.setTime(DateUtil.now());
        log.error(e.getMessage());
        return result;
    }


    /**
     * 未定义异常
     * @return

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public JSONResult<Object> defaultErrorHandler(Exception e){
        JSONResult<Object> result = new JSONResult<>();
        if (e instanceof HttpMessageNotReadableException) {
            result.setCode(400);
        }else{
            result.setCode(500);
        }
        result.setMessage(e.getMessage());
        result.setSuccess(false);
        result.setTime(DateUtil.now());
        log.error(e.toString());
        return result;
    }
     */

}
